import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import { Form, Card, Button, message } from 'antd';
import { eventTrack } from '@/utils/track';
import moment from 'moment';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { formItemLayout } from '@/components/UserForm';
import PersonInfo from '@/components/PersonInfo';
import SlidedTabs from '@/components/SlideTabs';
import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import { withRoutePage } from '@/utils/enhanceUtils';
import { getTempDetail } from '@/services/myRecruit/talentPool';
import JobApplication from './Components/JobApplication';
import TalentPoolForm from './Components/TalentPoolForm';
import styles from './TalentPoolList.less';
import PositionModal from './Components/PositionModal';

const EditTalentPool = ({ dispatch, form, user, talentPool, loading, ...rags }) => {
    const { authCode } = new AuthCode(rags.route.code);
    const talentCode = rags.location.query.code ? rags.location.query.code : '';

    let identity = ''; // 访问页面人的身份信息
    // 获取路由上的name值进行判断身份
    if (rags && rags.route.name === 'adminTalentPoolDetail') {
        identity = 'admin';
    } else {
        identity = 'user';
    }

    const [isEdit, setisEdit] = useState(false);
    const [visible, setvisible] = useState(false);
    // const [isSpinLoding, setisSpinLoding] = useState(true);
    // 文件信息
    const [showFileList, setShowFileList] = useState([]);
    const [uploadResource, setUploadResource] = useState(null);
    const [submitLoading, setsubmitLoading] = useState(false);
    const [required, setRequired] = React.useState(false);
    const User = user.currentUser; // 登陆人信息
    const jobList = talentPool.jobApplication; // 应聘职位表格
    const candidate = talentPool.candidateInfoEdit; // 候选人信息
    console.log(showFileList, 'showFileList');
    // SlidedTabs
    const [activeKey, setActiveKey] = useState('1');
    const tabs = [
        {
            label: '简历信息',
            key: '1'
        },
        {
            label: '应聘职位',
            key: '2'
        }
    ];
    // SlidedTabs

    /**
     * 获取登录人信息
     */
    const getUserInfo = () => {
        dispatch({
            type: 'userInfo/getUserInfo'
        });
    };
    // 获取候选人应聘职位
    const getquerycandidatesbytalent = () => {
        dispatch({
            type: 'talentPool/querycandidatesbytalent',
            payload: {
                talentCode
            }
        });
    };
    // 获取候选人用户信息
    const getOne = () => {
        dispatch({
            type: 'talentPool/getone',
            payload: {
                identity,
                talentCode
            },
            callback: data => {
                const { talentFile = [] } = data;
                setShowFileList(
                    talentFile.map(item => {
                        const { keyName, originName, url } = item;
                        const itemRetrun = {
                            uid: keyName,
                            keyName,
                            name: originName,
                            oldName: originName,
                            url
                        };
                        return itemRetrun;
                    })
                );
            }
        });
    };

    /**
     * 当点击编辑的时候，先储存一份候选人信息
     */
    const editInfo = () => {
        setisEdit(!isEdit);
    };
    const returnUp = () => {
        // 埋点
        eventTrack({
            eventName: 'personnel_management_recruit_talentPool_detail_edit_cancel_click'
        });
        form.resetFields();
        setisEdit(!isEdit);
    };

    // const getQuerylist = () =>
    //     querylist &&
    //     querylist.map(item => (
    //         <Option value={item.recruitCode} key={item.recruitCode}>
    //             {item.recruitName}
    //         </Option>
    //     ));
    const init = async () => {
        getUserInfo();
        // 编辑页面，假如没有用户code，为了避免页面报错，取消数据获取
        if (rags.location.query.code) {
            getOne();
            getquerycandidatesbytalent();
        }
        const res = await getTempDetail({
            // interviewArrangeCode: record.interviewArrangeCode,
            talentCode: rags.location.query.code ? rags.location.query.code : ''
        });
        if (res.data.registerStatus === 1) {
            setRequired(true); // 应聘登记表有填写过的人才更换校验规则
        }
        // 0未登记  1登记
        // 埋点
        eventTrack({
            eventName: 'personnel_management_recruit_talentPool_detail_click',
            eventProps: {
                label: '人才管理-人才详情'
            }
        });
        console.log('===============================================>res', res.data.registerStatus);
    };

    const saveInfo = values => {
        setsubmitLoading(true);
        dispatch({
            type: 'talentPool/updatetalent',
            payload: values,
            callback: res => {
                if (res.code === 10000) {
                    message.success('修改成功');
                    setisEdit(false);
                    // 提交成功之后需要请求数据更新表单（不然获取不到已提交数据的id）
                    // 埋点
                    eventTrack({
                        eventName: 'personnel_management_recruit_talentPool_detail_edit_submit_click',
                        eventProps: { status: '0' }
                    });
                    init();
                } else {
                    message.error(res.msg);
                    eventTrack({
                        eventName: 'personnel_management_recruit_talentPool_detail_edit_submit_click',
                        eventProps: { status: '1', error_info: res.msg }
                    });
                }
                setsubmitLoading(false);
            }
        });
    };
    /**
     * 表单提交
     */
    const handleSubmit = e => {
        e.preventDefault();
        form.validateFieldsAndScroll(async (err, values) => {
            console.log(values, 'values');
            if (!err) {
                const result = {
                    talentCode,
                    id: candidate.id,
                    talentName: candidate.talentName,
                    talentLeaderId: candidate.talentLeaderId,
                    talentPhone: candidate.talentPhone,
                    insertDate: candidate.insertDate
                };
                // 附件需要特殊处理
                const resourceRelationArr = [];
                if (uploadResource) {
                    resourceRelationArr.push(uploadResource);
                }
                const originData = form.getFieldsValue();
                // 下面日期判断直接使用招聘登记表的提交判断
                Object.keys(originData).forEach(key => {
                    const arr = key.split('_');
                    if (originData[key] || originData[key] === 0) {
                        if (arr[2]) {
                            if (!result[arr[0]]) {
                                result[arr[0]] = [];
                            }
                            if (!result[arr[0]][Number(arr[2])]) {
                                result[arr[0]][Number(arr[2])] = {};
                            } else if (
                                Object.keys(result[arr[0]][Number(arr[2])]).length > 0 &&
                                !result[arr[0]][Number(arr[2])].talentCode
                            ) {
                                result[arr[0]][Number(arr[2])].talentCode = talentCode;
                            }
                            if (originData[key] || originData[key] === 0) {
                                if (arr[1] === 'dateRange') {
                                    if (originData[key][0]) {
                                        result[arr[0]][Number(arr[2])].startTime = moment(originData[key][0]).format(
                                            'YYYY-MM-01'
                                        );
                                        result[arr[0]][Number(arr[2])].endTime = moment(originData[key][1]).format(
                                            'YYYY-MM-01'
                                        );
                                    }
                                } else if (originData[key] instanceof moment) {
                                    result[arr[0]][Number(arr[2])][arr[1]] = moment(originData[key]).format(
                                        'YYYY-MM-DD'
                                    );
                                } else {
                                    result[arr[0]][Number(arr[2])][arr[1]] = originData[key];
                                }
                            }
                        } else if (Array.isArray(originData[key])) {
                            result[arr[0]] = originData[key].join(',');
                        } else if (originData[key] instanceof moment) {
                            result[arr[0]] = moment(originData[key]).format('YYYY-MM-DD');
                        } else {
                            result[arr[0]] = originData[key];
                        }
                    }
                });
                const haveObjInArr = arrData => {
                    let ret = false;
                    for (let i = 0; i < arrData.length; i += 1) {
                        if (typeof arrData[i] === 'object') {
                            ret = true;
                            break;
                        }
                    }
                    return ret;
                };
                Object.keys(result).forEach(rKey => {
                    if (Array.isArray(result[rKey]) && haveObjInArr(result[rKey])) {
                        const newArr = [];
                        result[rKey].forEach(item => {
                            if (item && Object.keys(item).length > 0) {
                                const { id, talentCode: code, deleteFlag, ...otherField } = item;
                                const validField = Object.keys(otherField).find(field => {
                                    if (field) {
                                        return true;
                                    }
                                    return false;
                                });
                                newArr.push({ ...item, talentCode, deleteFlag: validField ? 0 : 1 });
                            }
                        });
                        result[rKey] = newArr;
                    }
                });
                const payload = {
                    ...result,
                    resourceRelation: resourceRelationArr,
                    talentNationalArea: result.talentNationalArea.split(','),
                    address: result.address.split(','),
                    talentBirth: result.talentBirth === '' ? null : result.talentBirth
                };
                console.log('===============================================>payload', payload);
                saveInfo(payload);
            }
        });
    };

    const setFileResource = (showFileListReturn, uploadResourceReturn) => {
        console.log(showFileListReturn, uploadResourceReturn, 123);
        setShowFileList(showFileListReturn);
        setUploadResource(uploadResourceReturn);
    };

    // 返回编辑按钮
    const returnEdit = () => {
        if (!isEdit) {
            return identity === 'admin' ? (
                <AuthComponent code={authCode('detail:edit')}>
                    <Button
                        type="primary"
                        onClick={() => {
                            eventTrack({
                                eventName: 'personnel_management_recruit_talentPool_detail_edit_click'
                            });
                            editInfo();
                        }}
                    >
                        编辑
                    </Button>
                </AuthComponent>
            ) : (
                <Button
                    type="primary"
                    onClick={() => {
                        editInfo();
                    }}
                >
                    编辑
                </Button>
            );
        }
        return '';
    };

    const addJobApplication = () => {
        // dispatch({
        //     type: 'talentPool/querylist',
        //     payload: {
        //         companyId: User.companyId,
        //         recruitSchedule: 'recruit_hiring'
        //     },
        //     callback: () => {
        //         setisSpinLoding(false);
        //     }
        // });
        setvisible(true);
    };
    const returnBtns = () => {
        const printBtn = (
            <Button
                type="primary"
                onClick={() => {
                    // 埋点
                    eventTrack({
                        eventName: 'personnel_management_recruit_talentPool_detail_print_click'
                    });
                    window.open(`/office/personnelManagement/recruit/talentPool/print?code=${talentCode}`);
                }}
            >
                打印简历
            </Button>
        );
        if (identity === 'admin') {
            return [
                printBtn,
                <AuthComponent code={authCode('detail:addjob')}>
                    <Button
                        type="primary"
                        onClick={() => {
                            // 埋点
                            eventTrack({
                                eventName: 'personnel_management_recruit_talentPool_detail_add_click'
                            });
                            addJobApplication();
                        }}
                    >
                        添加应聘职位
                    </Button>
                </AuthComponent>
            ];
        }
        return [
            printBtn,
            <Button
                type="primary"
                onClick={() => {
                    addJobApplication();
                }}
            >
                添加应聘职位
            </Button>
        ];
    };
    const getSexName = key => {
        if (key === '1') {
            return 'man';
        }
        if (key === '2') {
            return 'woman';
        }
        return '';
    };
    useEffect(() => {
        init();
    }, []);
    return (
        <PageHeaderWrapper>
            <Card bordered={false} style={{ padding: '24px 0' }} bodyStyle={{ padding: 0 }}>
                <PersonInfo
                    style={{ padding: '0 24px' }}
                    sex={getSexName(candidate.talentSex)}
                    name={candidate.talentName}
                    status=""
                    infos={[
                        {
                            label: '招聘负责',
                            value: candidate.talentLeaderName
                        }
                    ]}
                    // identity
                    btns={returnBtns()}
                />
                <SlidedTabs
                    cardStyle={{
                        height: 'calc(100vh - 400px)',
                        marginRight: 4,
                        padding: 0
                    }}
                    tabs={tabs}
                    activeKey={activeKey}
                    onChange={key => setActiveKey(key)}
                >
                    {refs => (
                        <div>
                            <div className={styles.title_edit}>
                                <h3 ref={refs[0].ref} className="vv-from-title" style={{ marginBottom: 0 }}>
                                    简历信息
                                </h3>
                                {candidate && candidate.isEdit ? returnEdit() : ''}
                            </div>

                            <Form className="form-Wrap" layout="horizontal" {...formItemLayout} onSubmit={handleSubmit}>
                                <TalentPoolForm
                                    required={required}
                                    isEdit={isEdit}
                                    enterType="edit"
                                    onReturn={() => {
                                        returnUp();
                                    }}
                                    showFileList={showFileList}
                                    uploadResource={uploadResource}
                                    onSetFileResource={setFileResource}
                                    form={form}
                                    user={User}
                                    companyId={rags.location.query.companyId ? rags.location.query.companyId : ''}
                                    identity={identity}
                                    candidate={candidate}
                                    submitLoading={submitLoading}
                                />
                            </Form>
                            <div
                                style={{
                                    background: 'rgba(232,232,232,1)',
                                    marginBottom: 15,
                                    height: 1
                                }}
                            />
                            <h3 ref={refs[1].ref} className="vv-from-title">
                                应聘职位
                            </h3>
                            <JobApplication data={jobList} />
                        </div>
                    )}
                </SlidedTabs>
            </Card>
            <PositionModal
                candidate={candidate}
                visible={visible}
                // isSpinLoding={isSpinLoding}
                setvisible={setvisible}
                query={rags.location.query}
                onGetquerycandidatesbytalent={() => {
                    getquerycandidatesbytalent();
                }}
            />
        </PageHeaderWrapper>
    );
};
export default withRoutePage(
    connect(({ loading, user, talentPool }) => ({
        loading,
        user,
        talentPool
    }))(Form.create()(EditTalentPool))
);
